package com.anbinh.doctor.fragment.lichkham;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager.LayoutParams;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.anbinh.doctor.DetailtActivity;
import com.anbinh.doctor.R;
import com.anbinh.doctor.adapter.DialogMenuAdapter;
import com.anbinh.doctor.model.Address;
import com.anbinh.doctor.model.DataResponse;
import com.anbinh.doctor.model.ItemMeu;
import com.anbinh.doctor.model.UserLogin;
import com.anbinh.doctor.request.controller.ServerController;
import com.anbinh.doctor.service.request.OnRequest;
import com.anbinh.doctor.utils.IRcallBak;
import com.anbinh.doctor.utils.Utils;
import com.lsjwzh.widget.materialloadingprogressbar.CircleProgressBar;
import com.wangjie.wheelview.WheelView;

public class FragmentEditLichKham extends SherlockFragment {
	private static final int START = 0;
	private static final int END = 1;
	private static FragmentEditLichKham fragment = null;
	private View mView;
	private WheelView mHourStart;
	private WheelView mMinStart;
	private CircleProgressBar loadding;

	private WheelView mHourStop;
	private WheelView mMinStop;
	private Calendar c;

	private Button btnBatdau;
	private Button btnKethuc;

	private LinearLayout line_start;
	private LinearLayout line_stop;
	private LinearLayout lineAppdung;
	private LinearLayout lineLaplai;

	private String hour_start = "";
	private String min_start = "";

	private String hour_end = "";
	private String min_end = "";

	private Bundle currentTimeRepeat = null;
	private Bundle currentLocation = null;
	private Bundle optionRepeat = null;
	private String mTungay = "";
	private String mDenngay = "";
	private Address address;
	private UserLogin userLogin;
	private FragmentLichkham mFragmentLk;
	private int doctor_address_id;
	private String time_slots;

	public static FragmentEditLichKham newInstance() {
		if (fragment == null) {
			fragment = new FragmentEditLichKham();
		}
		return fragment;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mFragmentLk = FragmentLichkham.newInstance();
		String time_start[] = mFragmentLk.getCurrentSchedules().getTime_from()
				.split(":");
		String time_end[] = mFragmentLk.getCurrentSchedules().getTime_to()
				.split(":");

		hour_start = time_start[0];
		min_start = time_start[1];
		hour_end = time_end[0];
		min_end = time_end[1];
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}

	@Override
	public void onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu,
			com.actionbarsherlock.view.MenuInflater inflater) {
		menu.add(0, R.id.dia_diem_kham, Menu.NONE, "Hoàn thành")
				.setIcon(R.drawable.ic_done)
				.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		checkUpdate();
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onResume() {
		super.onResume();
		((DetailtActivity) getActivity()).setActionBarTitle(getResources()
				.getString(R.string.cap_nhat_lich_kham));

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.fragment_add_lichkham, null);
		userLogin = Utils.getAccountModel(getActivity(), Utils.KEY_USER);
		return mView;
	}

	public List<String> getData(int last) {
		List<String> mHour = new ArrayList<String>();
		for (int i = 0; i <= last; i++) {
			if (i < 10) {
				mHour.add("0" + i);
			} else {
				mHour.add(i + "");
			}
		}
		return mHour;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		line_start = (LinearLayout) mView.findViewById(R.id.line_start);
		line_stop = (LinearLayout) mView.findViewById(R.id.line_stop);
		lineAppdung = (LinearLayout) mView.findViewById(R.id.lineAppdung);
		lineLaplai = (LinearLayout) mView.findViewById(R.id.lineLaplai);
		lineAppdung.setVisibility(View.GONE);
		lineLaplai.setVisibility(View.GONE);

		loadding = (CircleProgressBar) mView.findViewById(R.id.loadding);
		line_start.setVisibility(View.VISIBLE);
		line_stop.setVisibility(View.GONE);

		btnBatdau = (Button) mView.findViewById(R.id.btnBatdau);
		btnKethuc = (Button) mView.findViewById(R.id.btnKetthuc);
		btnBatdau.setSelected(true);
		btnKethuc.setSelected(false);

		mHourStart = (WheelView) mView.findViewById(R.id.hour_start);
		mMinStart = (WheelView) mView.findViewById(R.id.min_start);
		mHourStop = (WheelView) mView.findViewById(R.id.hour_stop);
		mMinStop = (WheelView) mView.findViewById(R.id.min_stop);

		setDataWhell(mHourStart, 24, START);
		setDataWhell(mMinStart, 60, START);

		setDataWhell(mHourStop, 24, END);
		setDataWhell(mMinStop, 60, END);

		btnBatdau.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				btnBatdau.setSelected(true);
				btnKethuc.setSelected(false);
				line_start.setVisibility(View.VISIBLE);
				line_stop.setVisibility(View.GONE);
				mHourStart.setSeletion(Integer.parseInt(hour_start));
				mMinStart.setSeletion(Integer.parseInt(min_start));
			}
		});

		btnKethuc.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				btnBatdau.setSelected(false);
				btnKethuc.setSelected(true);
				line_start.setVisibility(View.GONE);
				line_stop.setVisibility(View.VISIBLE);

				mHourStop.setSeletion(Integer.parseInt(hour_end));
				mMinStop.setSeletion(Integer.parseInt(min_end));

			}
		});

		mHourStart.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
			@Override
			public void onSelected(int selectedIndex, String item) {
				hour_start = item;
			}
		});

		mMinStart.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
			@Override
			public void onSelected(int selectedIndex, String item) {
				min_start = item;
			}
		});

		mHourStop.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
			@Override
			public void onSelected(int selectedIndex, String item) {
				hour_end = item;
			}
		});

		mMinStop.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
			@Override
			public void onSelected(int selectedIndex, String item) {
				min_end = item;
			}
		});

		final TextView spCa = (TextView) mView.findViewById(R.id.spCa);

		spCa.setText(mFragmentLk.getCurrentSchedules().getTime_slots()
				+ " phút/Ca");
		spCa.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showPopupMenu(Utils.getMenu(getActivity(), R.menu.time_block),
						getResources()
								.getString(R.string.chon_thoi_gian_moi_ca),
						new IRcallBak() {

							@Override
							public void onDisplay(int type, Bundle data) {
								currentTimeRepeat = data;
								time_slots = currentTimeRepeat
										.getString(Utils.TITLE);
								spCa.setText(data.getString(Utils.TITLE)
										+ " phút");
							}
						});
			}
		});

		final TextView spDiadiem = (TextView) mView
				.findViewById(R.id.spDiadiem);
		spDiadiem.setText(mFragmentLk.getCurrentSchedules().getAddress());
		doctor_address_id = Integer.parseInt(mFragmentLk.getCurrentSchedules()
				.getDoctor_address_id());
		spDiadiem.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showPopupMenu(Utils.getListLocation(address), getResources()
						.getString(R.string.chon_dia_diem), new IRcallBak() {

					@Override
					public void onDisplay(int type, Bundle data) {
						currentLocation = data;
						spDiadiem.setText(data.getString(Utils.TITLE));
						doctor_address_id = currentLocation.getInt(Utils.KEY);
					}
				});
			}
		});

		final TextView spReapeat = (TextView) mView
				.findViewById(R.id.spReapeat);
		spReapeat.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showPopupMenu(Utils.getMenu(getActivity(), R.menu.time_repeat),
						"Cài đặt", new IRcallBak() {

							@Override
							public void onDisplay(int type, Bundle data) {
								optionRepeat = data;
								spReapeat.setText(data.getString(Utils.TITLE));
								int key = data.getInt(Utils.KEY);
								switch (key) {
								case R.id.no_repeat:
									mTungay = "";
									mDenngay = "";
									break;
								default:
									break;
								}
							}
						});
			}
		});

		onLoadData();
	}

	public void onLoadData() {
		loadding.setVisibility(View.VISIBLE);
		Utils.disableEnableControls(false, mView);

		String token = userLogin.getData().getToken();
		ServerController.getInstance(getActivity()).reuquestListAddress(token,
				0, new OnRequest<Address>() {

					@Override
					public void onSuccess(Address data) {
						if (getActivity() == null)
							return;

						loadding.setVisibility(View.INVISIBLE);
						Utils.disableEnableControls(true, mView);
						if (getActivity() == null)
							return;
						address = data;

					}

					@Override
					public void onError(int errorCode, String message) {
						loadding.setVisibility(View.INVISIBLE);
					}
				});
	}

	public class DatePickerFragment extends DialogFragment implements
			DatePickerDialog.OnDateSetListener {
		TextView textView;

		public DatePickerFragment(TextView textView) {
			this.textView = textView;
		}

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			// Use the current date as the default date in the picker
			final Calendar c = Calendar.getInstance();
			int year = c.get(Calendar.YEAR);
			int month = c.get(Calendar.MONTH);
			int day = c.get(Calendar.DAY_OF_MONTH);

			// Create a new instance of DatePickerDialog and return it
			return new DatePickerDialog(getActivity(), this, year, month, day);
		}

		public void onDateSet(DatePicker view, int year, int month, int day) {
			month++;

			textView.setText(Utils
					.getDateFormat(year + "-" + month + "-" + day));
		}
	}

	public void setDataWhell(WheelView wheelView, int last, int key) {
		c = Calendar.getInstance();
		wheelView.setOffset(1);
		if (last == 24) {
			switch (key) {
			case START:
				wheelView.setSeletion(Integer.parseInt(hour_start));
				break;
			case END:
				wheelView.setSeletion(Integer.parseInt(hour_end));
				break;
			}
		} else {
			switch (key) {
			case START:
				wheelView.setSeletion(Integer.parseInt(min_start));
				break;
			case END:
				wheelView.setSeletion(Integer.parseInt(min_end));
				break;
			}
		}
		wheelView.setItems(getData(last));
	}

	public void showPopupMenu(final List<ItemMeu> list, String title,
			final IRcallBak callBak) {
		final Dialog dialog = new Dialog(getActivity());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.getWindow().setBackgroundDrawableResource(
				R.drawable.abs__menu_dropdown_panel_holo_light);
		dialog.setCanceledOnTouchOutside(true);
		DisplayMetrics metrics = new DisplayMetrics();
		((Activity) getActivity()).getWindowManager().getDefaultDisplay()
				.getMetrics(metrics);

		int width = metrics.widthPixels;

		dialog.setContentView(R.layout.dialog_menu_lich_kham);
		dialog.getWindow().setLayout(width - 60, LayoutParams.WRAP_CONTENT);

		TextView lblTitle = (TextView) dialog.findViewById(R.id.lblTitle);
		lblTitle.setText(title);
		ListView mListview = (ListView) dialog.findViewById(R.id.listView1);
		DialogMenuAdapter adapter = new DialogMenuAdapter(getActivity(),
				R.layout.item_menu_dialog, list);
		mListview.setAdapter(adapter);
		mListview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				Bundle bundle = new Bundle();
				bundle.putInt(Utils.KEY, list.get(position).getRegId());
				bundle.putString(Utils.TITLE, list.get(position).getTitle());
				dialog.dismiss();
				callBak.onDisplay(0, bundle);
			}

		});
		dialog.show();
	}

	public void checkUpdate() {
		Utils.disableEnableControls(false, mView);
		loadding.setVisibility(View.VISIBLE);
		int id = mFragmentLk.getCurrentSchedules().getId();
		ServerController.getInstance(getActivity()).requestCheckUpdate(
				userLogin.getData().getToken(), id, "update", -1,
				new OnRequest<DataResponse>() {

					@Override
					public void onSuccess(DataResponse data) {
						if (getActivity() == null)
							return;
						if (data.getResponsecode() == 201) {
							loadding.setVisibility(View.GONE);
							Utils.disableEnableControls(true, mView);
							showDialogConfirm(data.getDescription());
						} else {
							onPushData();
						}

					}

					@Override
					public void onError(int errorCode, String message) {
						loadding.setVisibility(View.INVISIBLE);
						Utils.disableEnableControls(false, mView);

					}
				});
	}

	public void showDialogConfirm(String message) {
		final Dialog dialog = new Dialog(getActivity());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.getWindow().setBackgroundDrawableResource(
				android.R.color.transparent);
		dialog.setCanceledOnTouchOutside(true);
		DisplayMetrics metrics = new DisplayMetrics();
		((Activity) getActivity()).getWindowManager().getDefaultDisplay()
				.getMetrics(metrics);

		int width = metrics.widthPixels;

		dialog.setContentView(R.layout.dialog_tamhoan);
		dialog.getWindow().setLayout(width - 60, LayoutParams.WRAP_CONTENT);
		TextView lblTitle = (TextView) dialog.findViewById(R.id.lblTitle);
		lblTitle.setText(message);
		TextView btnCo = (TextView) dialog.findViewById(R.id.btnCo);

		btnCo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
				onPushData();
			}
		});

		TextView btnKo = (TextView) dialog.findViewById(R.id.btnKo);
		btnKo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

		dialog.show();

	}

	public void onPushData() {
		String date = FragmentLichkham.newInstance().getmCurrentDay();
		String start = hour_start + ":" + min_start;
		String end = hour_end + ":" + min_end;
		String date_to = "";
		String date_repeat = "";
		loadding.setVisibility(View.VISIBLE);
		Utils.disableEnableControls(false, mView);
		int id = mFragmentLk.getCurrentSchedules().getId();
		ServerController.getInstance(getActivity()).requestAddLichKham(
				userLogin.getData().getToken(), date, start, end,
				doctor_address_id, time_slots, date_to, date_repeat, id, -1,
				new OnRequest<DataResponse>() {

					@Override
					public void onSuccess(DataResponse data) {
						loadding.setVisibility(View.GONE);
						Utils.disableEnableControls(true, mView);

						if (getActivity() == null)
							return;
						if (data.getResponsecode() >= 0) {
							Intent intent = new Intent();
							intent.putExtra(Utils.KEY, Utils.EDIT_LICH_KHAM);
							getActivity().setResult(Integer.MAX_VALUE, intent);
							getActivity().finish();
						}
					}

					@Override
					public void onError(int errorCode, String message) {
						loadding.setVisibility(View.GONE);
						Utils.disableEnableControls(true, mView);

					}
				});

	}
}
